<?php

if ($env['shop']['sagepay']['mode'] == 'live' and (!isset($_SERVER['HTTPS']) or !$_SERVER['HTTPS'])) {
	// force https
	header("Location: https://{$site['domain_name']}{$_SERVER['REQUEST_URI']}");
	exit;
}

if (isset($path[0]) and $path[0] == 'complete') {
	$order_id = $path[1];
	echo $order_id;
	return;
}

if (count($basket->lines()) == 0) {
	// can't check out with no basket content
	header("Location: {$page['full_path']}basket/");
	exit;
}

// set up the sagepay object
$sagepay = new SagePay($env['shop']['sagepay']['vendorid'], $env['shop']['sagepay']['mode']);

/*
 * We need to handle this seperately from $_POST as if it's a 3d Response, we'll
 * override it.
 *
 */
$sagepay_post_data = isset($_REQUEST['sagepay']) ? $_REQUEST['sagepay'] : array();

if (SagePay::is3dResponse()) {
	$sagepay = SagePay::recover3d();
	$sagepay->complete3d();
	$sagepay_post_data = $sagepay->post;
}

$charge_vat = 1;
if (isset($sagepay_post_data['DeliveryCountryID'])) {
	// we need to do this before $basket is converted to an array with export()
	$basket->shipping_band = $db->fetchOne("SELECT shipping_band FROM shop_countries WHERE country_id=?", $sagepay_post_data['DeliveryCountryID']);
	$charge_vat            = $db->fetchOne("SELECT charge_vat FROM cms_countries WHERE id=?", $sagepay_post_data['DeliveryCountryID']);
}
$smarty->assign('charge_vat', $charge_vat);

$smarty->assign('countries', $db->fetchAll("SELECT * FROM cms_countries c LEFT JOIN shop_countries s ON c.id=s.country_id ORDER BY title"));
$basket_exported = $basket->export();
$smarty->assign('basket', $basket_exported);




// add a line for each basket line
foreach($basket_exported['lines'] as $line) {
	$sagepay->addLine($line['product']['title'], $line['quantity'], $line['product']['total_price_excl']/$line['quantity'], ($charge_vat ? $line['product']['total_vat']/$line['quantity'] : 0));
}




// caculate the delivery cost based on number of deliveries and chosen options
$delivery_cost_excl = 0;
$delivery_cost_vat  = 0;
if (isset($_REQUEST['sagepay']['Deliveries']) and $_REQUEST['sagepay']['Deliveries'] == 'split') {
	foreach($basket_exported['shipments'] as $key => $shipment) {
		if (isset($_REQUEST['sagepay']['Delivery']['split'])) {
			if (isset($shipment['shipping'][$_REQUEST['sagepay']['Delivery']['split'][$key]])) {
				$delivery_cost_excl += $shipment['shipping'][$_REQUEST['sagepay']['Delivery']['split'][$key]]['price_excl_vat'];
				$delivery_cost_vat  += $shipment['shipping'][$_REQUEST['sagepay']['Delivery']['split'][$key]]['price_vat'];
				$sagepay->addLine($shipment['shipping'][$_REQUEST['sagepay']['Delivery']['split'][$key]]['title'], 1, $shipment['shipping'][$_REQUEST['sagepay']['Delivery']['split'][$key]]['price_excl_vat'], ($charge_vat ? $shipment['shipping'][$_REQUEST['sagepay']['Delivery']['split'][$key]]['price_vat'] : 0));
			} else {
				$delivery_cost_excl += $shipment['shipping'][array_value_at(array_keys($shipment['shipping']), 0)]['price_excl_vat'];
				$delivery_cost_vat  += $shipment['shipping'][array_value_at(array_keys($shipment['shipping']), 0)]['price_vat'];
				$sagepay->addLine($shipment['shipping'][array_value_at(array_keys($shipment['shipping']), 0)]['title'], 1, $shipment['shipping'][array_value_at(array_keys($shipment['shipping']), 0)]['price_excl_vat'], ($charge_vat ? $shipment['shipping'][array_value_at(array_keys($shipment['shipping']), 0)]['price_vat'] : 0));
			}
		}
	}
} else {
	if (isset($_REQUEST['sagepay']['Delivery']['single']) and isset($basket_exported['shipping'][$_REQUEST['sagepay']['Delivery']['single'][0]])) {
		$delivery_cost_excl += $basket_exported['shipping'][$_REQUEST['sagepay']['Delivery']['single'][0]]['price_excl_vat'];
		$delivery_cost_vat  += $basket_exported['shipping'][$_REQUEST['sagepay']['Delivery']['single'][0]]['price_vat'];
		$sagepay->addLine($basket_exported['shipping'][$_REQUEST['sagepay']['Delivery']['single'][0]]['title'], 1, $basket_exported['shipping'][$_REQUEST['sagepay']['Delivery']['single'][0]]['price_excl_vat'], ($charge_vat ? $basket_exported['shipping'][$_REQUEST['sagepay']['Delivery']['single'][0]]['price_vat'] : 0));
	} else {
		$delivery_cost_excl += $basket_exported['shipping'][array_value_at(array_keys($basket_exported['shipping']), 0)]['price_excl_vat'];
		$delivery_cost_vat  += $basket_exported['shipping'][array_value_at(array_keys($basket_exported['shipping']), 0)]['price_vat'];
		$sagepay->addLine($basket_exported['shipping'][array_value_at(array_keys($basket_exported['shipping']), 0)]['title'], 1, $basket_exported['shipping'][array_value_at(array_keys($basket_exported['shipping']), 0)]['price_excl_vat'], ($charge_vat ? $basket_exported['shipping'][array_value_at(array_keys($basket_exported['shipping']), 0)]['price_vat'] : 0));
	}
}





$errors = array();






if (isset($_POST['checkout_login'])) {
	// login the user - we can't use the default login function as it uses different field names.
	$user = $db->fetchRow("SELECT * FROM cms_users WHERE site_id=? AND email=?", array($site['id'], $_POST['sagepay']['CustomerEmail']));
	if ($user and Password::auth($_POST['sagepay']['LoginPassword'], $user['password'])) {
		session_regenerate_id();
		$user['custom_fields'] = $db->fetchRow("SELECT * FROM cms_users_custom_{$site['id']} WHERE user_id=?", $user['id']);
		$user['access_rights'] = unserialize($user['access_rights']);
		$_SESSION['login'] = array('user' => $user, 'timestamp' => time());
		$db->update('cms_users', array('loggedin' => new Zend_Db_Expr('NOW()'), 'loggedin_ip' => $_SERVER['REMOTE_ADDR']));
		unset($user);
	} else {
		$errors['login'] = 1;
	}
	$smarty->assign('errors', $errors);
}
if (isset($_SESSION['login'])) {
	// if we're logged in, then get previously used addresses
	$addresses = $db->fetchAll("SELECT a.*, c.title AS country FROM shop_users_addresses a LEFT JOIN cms_countries c ON a.country_id=c.id WHERE user_id=?", $_SESSION['login']['user']['id']);
	$smarty->assign('addresses', $addresses);
}





if (isset($_POST['checkout_complete'])) {
	// attempt to checkout with sagepay

	// first off, we'll check for errors, so SagePay doesn't have to.
	if (!preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+\.([a-zA-Z0-9\._-]+)+$/", $_POST['sagepay']['CustomerEmail'])) $errors['CustomerEmail'] = 1;
	if (!$sagepay_post_data['DeliveryFirstnames']) $errors['DeliveryFirstnames'] = 1;
	if (!$sagepay_post_data['DeliverySurname'])    $errors['DeliverySurname']    = 1;
	if (!$sagepay_post_data['DeliveryAddress1'])   $errors['DeliveryAddress1']   = 1;
	if (!$sagepay_post_data['DeliveryCity'])       $errors['DeliveryCity']       = 1;
	if (!$sagepay_post_data['DeliveryPostCode'])   $errors['DeliveryPostCode']   = 1;
	if (!$sagepay_post_data['DeliveryCountryID'])  $errors['DeliveryCountryID']  = 1;
	if ($db->fetchOne("SELECT iso2 FROM cms_countries WHERE id=?", $sagepay_post_data['DeliveryCountryID']) == 'US' and !$sagepay_post_data['DeliveryState']) $errors['DeliveryState'] = 1;
	if (!$sagepay_post_data['DeliveryPhone'])      $errors['DeliveryPhone']      = 1;
	
	if ($sagepay_post_data['BillingAddress'] == 'different') {
		if (!$sagepay_post_data['BillingFirstnames']) $errors['BillingFirstnames'] = 1;
		if (!$sagepay_post_data['BillingSurname'])    $errors['BillingSurname']    = 1;
		if (!$sagepay_post_data['BillingAddress1'])   $errors['BillingAddress1']   = 1;
		if (!$sagepay_post_data['BillingCity'])       $errors['BillingCity']       = 1;
		if (!$sagepay_post_data['BillingPostCode'])   $errors['BillingPostCode']   = 1;
		if (!$sagepay_post_data['BillingCountryID'])  $errors['BillingCountryID']  = 1;
		if ($db->fetchOne("SELECT iso2 FROM cms_countries WHERE id=?", $sagepay_post_data['BillingCountryID']) == 'US' and !$sagepay_post_data['BillingState']) $errors['BillingState'] = 1;
		if (!$sagepay_post_data['BillingPhone'])      $errors['BillingPhone']      = 1;
	}
	
	if (!isset($sagepay_post_data['Delivery'])) $errors['Delivery'] = 1;
	
	if (isset($sagepay_post_data['RegisterPassword1']) and $sagepay_post_data['RegisterPassword1'] or isset($sagepay_post_data['RegisterPassword2']) and $sagepay_post_data['RegisterPassword2']) {
		if ($sagepay_post_data['RegisterPassword1'] != $sagepay_post_data['RegisterPassword2']) $errors['RegisterPassword'] = 'MATCH';
		elseif (!preg_match((isset($env['password']['regex']) ? $env['password']['regex'] : '/.+'), $sagepay_post_data['RegisterPassword1'])) $errors['RegisterPassword'] = 'VALID';
	}
	
	if (!preg_match('/\d{12,20}/', preg_replace('/[^\d]/', '', $sagepay_post_data['CardNumber']))) $errors['CardNumber'] = 1;
	if (!$sagepay_post_data['ExpiryDateMM'] or !$sagepay_post_data['ExpiryDateYY']) $errors['ExpiryDate'] = 1;
	if (!$sagepay_post_data['CV2']) $errors['CV2'] = 1;
	
	if (!isset($sagepay_post_data['TermsAndConditions'])) $errors['TermsAndConditions'] = 1;
	
	if (count($errors) == 0) {
		// proceed with sagepay.
		$sagepay->VendorTxCode = $basket_exported['reference'] . '-' . time();
		
		$sagepay->Amount       = $basket_exported['total_price_excl'] + $delivery_cost_excl;
		if ($charge_vat) $sagepay->Amount += $basket_exported['total_vat'] + $delivery_cost_vat;
		$sagepay->Currency     = isset($env['sagepay']['currency']) ? $env['sagepay']['currency'] : 'GBP';
		$sagepay->Description  = "Basket reference {$basket_exported['reference']}";
		$sagepay->BasketReference = $basket_exported['reference'];
		if (isset($_SESSION['login'])) $sagepay->UserID = $_SESSION['login']['user']['id'];
		
		// sagepay needs dates as MMDD so combine the data from the form
		$sagepay->StartDate = $_POST['sagepay']['StartDateMM'] . $_POST['sagepay']['StartDateYY'];
		$sagepay->ExpiryDate = $_POST['sagepay']['ExpiryDateMM'] . $_POST['sagepay']['ExpiryDateYY'];
		
		// insert all data from the form into the sagepay object
		foreach($sagepay_post_data as $key => $value) {
			if ($sagepay_post_data['BillingAddress'] == 'same' and preg_match("/^Billing/", $key)) continue;
			$sagepay->$key = $value;
			if ($sagepay_post_data['BillingAddress'] == 'same' and preg_match("/^Delivery/", $key)) {
				$key = preg_replace("/^Delivery/", 'Billing', $key);
				$sagepay->$key = $value;
			}
		}
		
		$sagepay->CardHolder = $sagepay->BillingFirstnames . ' ' . $sagepay->BillingSurname;
		$sagepay->BillingCountry = $db->fetchOne("SELECT iso2 FROM cms_countries WHERE id=?", $sagepay->BillingCountryID);
		$sagepay->DeliveryCountry = $db->fetchOne("SELECT iso2 FROM cms_countries WHERE id=?", $sagepay->DeliveryCountryID);
		
		// record the basket - just so that we can be sure it hasn't been modified
		// when we record it.
		$sagepay->BasketArray = $basket_exported;
		
		$sagepay->post = $_POST['sagepay'];
		
		// register the transaction
		$sagepay->register();
		
		// if the status is 3DAUTH, then we're off for 3D authentication.
		// assign data for forwarding.
		if ($sagepay->status() == '3DAUTH') {
			$smarty->assign('ACSURL', $sagepay->result['ACSURL']);
			$smarty->assign('PaReq', $sagepay->result['PAReq']);
			$smarty->assign('MD', $sagepay->result['MD']);
			
		}
		
		// if the status is anything other than OK, then something's gone
		// wrong.
		elseif ($sagepay->status() != 'OK' and $sagepay->result['Errors']) {
			$errors = $sagepay->result['Errors'];
		}
	}
	
} 





elseif (isset($_SERVER['HTTP_X_REQUESTED_WITH']) and $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
	// update the shipping options
	header('Content-type: text/xml');
	//print_r($sagepay_post_data);
	$smarty->assign('sagepay_post_data', $sagepay_post_data);
	$smarty->assign('delivery_cost', $delivery_cost_excl + ($charge_vat ? $delivery_cost_vat : 0));
	$smarty->assign('total_cost', $basket_exported['total_price_excl'] + $delivery_cost_excl + ($charge_vat ? $basket_exported['total_vat'] + $delivery_cost_vat : 0));
	$smarty->display('shop/checkout_delivery.tpl.taconite');
	return;
} 



// record the order.
if ($sagepay->status() == 'OK') {
	
	$basket->destroy();
	$basket = new Basket();
	$smarty->assign('basket', $basket->export());
	
	if (!isset($_SESSION['login']) and isset($sagepay->RegisterPassword1)) {
		$user = new User();
		$user->user['core']['email']      = $sagepay->CustomerEmail;
		$user->user['core']['username']   = $sagepay->CustomerEmail;
		$user->user['password1']          = $sagepay->RegisterPassword1;
		$user->user['password2']          = $sagepay->RegisterPassword1;
		$user->user['core']['first_name'] = $sagepay->BillingFirstnames;
		$user->user['core']['last_name']  = $sagepay->BillingSurname;
		$user->user['core']['display_name'] = $sagepay->BillingFirstnames . ' ' . $sagepay->BillingSurname;
		$user->save();
		$user = $db->fetchRow("SELECT * FROM cms_users WHERE site_id=? AND email=?", array($site['id'], $sagepay->CustomerEmail));
		session_regenerate_id();
		$user['custom_fields'] = $db->fetchRow("SELECT * FROM cms_users_custom_{$site['id']} WHERE user_id=?", $user['id']);
		$user['access_rights'] = unserialize($user['access_rights']);
		$_SESSION['login'] = array('user' => $user, 'timestamp' => time());
		$db->update('cms_users', array('loggedin' => new Zend_Db_Expr('NOW()'), 'loggedin_ip' => $_SERVER['REMOTE_ADDR']));
		unset($user);
	}
	
	$db->insert('shop_orders', array(
		'site_id'    => $site['id'],
		'user_id'    => isset($_SESSION['login']) ? $_SESSION['login']['user']['id'] : null,
		'ip_address' => $_SERVER['REMOTE_ADDR'],
		'email'      => $sagepay->CustomerEmail,
		'billing_first_name' => $sagepay->BillingFirstnames,
		'billing_last_name'  => $sagepay->BillingSurname,
		'billing_address_1'  => $sagepay->BillingAddress1,
		'billing_address_2'  => $sagepay->BillingAddress2,
		'billing_city'       => $sagepay->BillingCity,
		'billing_state'      => $sagepay->BillingState,
		'billing_postcode'   => $sagepay->BillingPostCode,
		'billing_country_id' => $sagepay->BillingCountryID,
		'billing_phone'      => $sagepay->BillingPhone
	));
	$order_id = $db->lastInsertId();
	$smarty->assign('order_id', $order_id);
	
	$db->insert('shop_orders_transactions', array(
		'order_id'               => $order_id,
		'method'                 => 'sagepay',
		'amount'                 => $sagepay->Amount,
		'sagepay_VendorTxCode'   => $sagepay->VendorTxCode,
		'sagepay_VPSTxId'        => $sagepay->result['VPSTxId'],
		'sagepay_SecurityKey'    => $sagepay->result['SecurityKey'],
		'sagepay_TxAuthNo'       => $sagepay->result['TxAuthNo'],
		'sagepay_AVSCV2'         => $sagepay->result['AVSCV2'],
		'sagepay_AddressResult'  => $sagepay->result['AddressResult'],
		'sagepay_PostCodeResult' => $sagepay->result['PostCodeResult'],
		'sagepay_CV2Result'      => $sagepay->result['CV2Result'],
		'sagepay_3DSecureStatus' => $sagepay->result['3DSecureStatus']
	));
	
	if (isset($_SESSION['login'])) {
		if (!$db->fetchOne("SELECT id FROM shop_users_addresses WHERE user_id=? AND first_name=? AND last_name=? AND address_1=? AND address_2=? AND city=? AND state=? AND postcode=? AND country_id=? AND phone=? AND type='billing'", array($_SESSION['login']['user']['id'], $sagepay->BillingFirstnames, $sagepay->BillingSurname, $sagepay->BillingAddress1, $sagepay->BillingAddress2, $sagepay->BillingCity, $sagepay->BillingState, $sagepay->BillingPostCode, $sagepay->BillingCountryID, $sagepay->BillingPhone))) {
			$db->insert('shop_users_addresses', array(
				'user_id'    => $_SESSION['login']['user']['id'],
				'first_name' => $sagepay->BillingFirstnames,
				'last_name'  => $sagepay->BillingSurname,
				'address_1'  => $sagepay->BillingAddress1,
				'address_2'  => $sagepay->BillingAddress2,
				'city'       => $sagepay->BillingCity,
				'state'      => $sagepay->BillingState,
				'postcode'   => $sagepay->BillingPostCode,
				'country_id' => $sagepay->BillingCountryID,
				'phone'      => $sagepay->BillingPhone,
				'type'       => 'billing'
			));
		}
		if (!$db->fetchOne("SELECT id FROM shop_users_addresses WHERE user_id=? AND first_name=? AND last_name=? AND address_1=? AND address_2=? AND city=? AND state=? AND postcode=? AND country_id=? AND phone=? AND type='delivery'", array($_SESSION['login']['user']['id'], $sagepay->DeliveryFirstnames, $sagepay->DeliverySurname, $sagepay->DeliveryAddress1, $sagepay->DeliveryAddress2, $sagepay->DeliveryCity, $sagepay->DeliveryState, $sagepay->DeliveryPostCode, $sagepay->DeliveryCountryID, $sagepay->DeliveryPhone))) {
			$db->insert('shop_users_addresses', array(
				'user_id'    => $_SESSION['login']['user']['id'],
				'first_name' => $sagepay->DeliveryFirstnames,
				'last_name'  => $sagepay->DeliverySurname,
				'address_1'  => $sagepay->DeliveryAddress1,
				'address_2'  => $sagepay->DeliveryAddress2,
				'city'       => $sagepay->DeliveryCity,
				'state'      => $sagepay->DeliveryState,
				'postcode'   => $sagepay->DeliveryPostCode,
				'country_id' => $sagepay->DeliveryCountryID,
				'phone'      => $sagepay->DeliveryPhone,
				'type'       => 'delivery'
			));
		}
	}
	if ($sagepay->Deliveries == 'split') {
		foreach($sagepay->BasketArray['shipments'] as $key => $delivery) {
			
			$db->insert('shop_orders_deliveries', array(
				'order_id' => $order_id,
				'delivery_first_name' => $sagepay->DeliveryFirstnames,
				'delivery_last_name'  => $sagepay->DeliverySurname,
				'delivery_address_1'  => $sagepay->DeliveryAddress1,
				'delivery_address_2'  => $sagepay->DeliveryAddress2,
				'delivery_city'       => $sagepay->DeliveryCity,
				'delivery_state'      => $sagepay->DeliveryState,
				'delivery_postcode'   => $sagepay->DeliveryPostCode,
				'delivery_country_id' => $sagepay->DeliveryCountryID,
				'delivery_phone'      => $sagepay->DeliveryPhone,
				'price_excl_vat'      => $delivery['shipping'][$sagepay->Delivery['split'][$key]]['price_excl_vat'],
				'vat'                 => ($charge_vat ? $delivery['shipping'][$sagepay->Delivery['split'][$key]]['price_vat'] : null),
				'delivery_method'     => $delivery['shipping'][$sagepay->Delivery['split'][$key]]['title'],
				'tracking_url'        => $delivery['shipping'][$sagepay->Delivery['split'][$key]]['tracking_url']
				
			));
			$delivery_id = $db->lastInsertId();
			foreach($delivery['lines'] as $line) {
				$attributes = $db->fetchAll("SELECT title, value FROM shop_products_attributes_values pav JOIN shop_products_attributes pa ON pav.attribute_id=pa.id WHERE pav.product_id=?", $line['product_id']);
				$attributes_text = '';
				foreach($attributes as $attribute) {
					$attributes_text .= $attribute['title'] . ': ' . $attribute['value'] . "\n";
				}
				$db->insert('shop_orders_lines', array(
					'order_id'       => $order_id,
					'delivery_id'    => $delivery_id,
					'product_id'     => $line['product_id'],
					'code'           => $line['product']['code'],
					'subcode'        => $line['product']['subcode'],
					'title'          => $line['product']['title'],
					'attributes'     => $attributes_text,
					'price_excl_vat' => $line['product']['total_price_excl'],
					'vat'            => ($charge_vat ? $line['product']['total_vat'] : null),
					'quantity'       => $line['quantity']
				));
				$line_id = $db->lastInsertId();

				foreach($line['product']['simpleattributes'] as $simpleattribute) {
					$db->insert('shop_orders_lines_simpleattributes', array(
						'line_id'            => $line_id,
						'simpleattribute_id' => $simpleattribute['simpleattribute_id'],
						'title'              => $simpleattribute['title'],
						'value'              => $simpleattribute['value'],
						'price'              => $simpleattribute['price'],
						'sort'               => $simpleattribute['sort']
					));
				}
				
				$db->update('shop_products', array('purchase_count' => new Zend_Db_Expr("purchase_count+{$db->quote($line['quantity'])}")), $db->quoteInto('code=?', $line['product']['code']));
			}
			
		}
	} 
	
	else {
		$db->insert('shop_orders_deliveries', array(
			'order_id' => $order_id,
			'delivery_first_name' => $sagepay->DeliveryFirstnames,
			'delivery_last_name'  => $sagepay->DeliverySurname,
			'delivery_address_1'  => $sagepay->DeliveryAddress1,
			'delivery_address_2'  => $sagepay->DeliveryAddress2,
			'delivery_city'       => $sagepay->DeliveryCity,
			'delivery_state'      => $sagepay->DeliveryState,
			'delivery_postcode'   => $sagepay->DeliveryPostCode,
			'delivery_country_id' => $sagepay->DeliveryCountryID,
			'delivery_phone'      => $sagepay->DeliveryPhone,
			'price_excl_vat'      => $sagepay->BasketArray['shipping'][$sagepay->Delivery['single'][0]]['price_excl_vat'],
			'vat'                 => ($charge_vat ? $sagepay->BasketArray['shipping'][$sagepay->Delivery['single'][0]]['price_vat'] : null),
			'delivery_method'     => $sagepay->BasketArray['shipping'][$sagepay->Delivery['single'][0]]['title'],
			'tracking_url'        => $sagepay->BasketArray['shipping'][$sagepay->Delivery['single'][0]]['tracking_url']
		));
		$delivery_id = $db->lastInsertId();
		
		foreach($sagepay->BasketArray['lines'] as $line) {
			$attributes = $db->fetchAll("SELECT title, value FROM shop_products_attributes_values pav JOIN shop_products_attributes pa ON pav.attribute_id=pa.id WHERE pav.product_id=?", $line['product_id']);
			$attributes_text = '';
			foreach($attributes as $attribute) {
				$attributes_text .= $attribute['title'] . ': ' . $attribute['value'] . "\n";
			}
			
			$db->insert('shop_orders_lines', array(
				'order_id'       => $order_id,
				'delivery_id'    => $delivery_id,
				'product_id'     => $line['product_id'],
				'code'           => $line['product']['code'],
				'subcode'        => $line['product']['subcode'],
				'title'          => $line['product']['title'],
				'attributes'     => $attributes_text,
				'price_excl_vat' => $line['product']['total_price_excl'],
				'vat'            => ($charge_vat ? $line['product']['total_vat'] : null),
				'quantity'       => $line['quantity']
			));
			$line_id = $db->lastInsertId();
			
			foreach($line['product']['simpleattributes'] as $simpleattribute) {
				$db->insert('shop_orders_lines_simpleattributes', array(
					'line_id'            => $line_id,
					'simpleattribute_id' => $simpleattribute['simpleattribute_id'],
					'title'              => $simpleattribute['title'],
					'value'              => $simpleattribute['value'],
					'price'              => $simpleattribute['price'],
					'sort'               => $simpleattribute['sort']
				));
			}
			
			$db->update('shop_products', array('purchase_count' => new Zend_Db_Expr("purchase_count+{$db->quote($line['quantity'])}")), $db->quoteInto('code=?', $line['product']['code']));
			
		}
	}
	
	$order = $db->fetchRow("SELECT o.*, c.title AS billing_country FROM shop_orders o LEFT JOIN cms_countries c ON o.billing_country_id=c.id WHERE site_id=? AND o.id=?", array($site['id'], $order_id));
	list($order['ip_address_country'], $order['ip_address_country_id']) = array_values($db->fetchRow("SELECT country_name, c.id FROM cms_iptoc ip LEFT JOIN cms_countries c ON ip.country_code2=c.iso2 WHERE INET_ATON(?) >= ip_from AND INET_ATON(?) <= ip_to", array($order['ip_address'], $order['ip_address'])));
	$order['transactions'] = $db->fetchAll("SELECT * FROM shop_orders_transactions WHERE order_id=?", $order['id']);
	$order['deliveries'] = $db->fetchAll("SELECT d.*, c.title AS delivery_country FROM shop_orders_deliveries d LEFT JOIN cms_countries c ON d.delivery_country_id=c.id WHERE order_id=?", $order['id']);
	$order['delivery_price_excl_vat'] = 0;
	$order['delivery_vat']            = 0;
	foreach($order['deliveries'] as &$delivery) {
		$delivery['lines'] = $db->fetchAll("SELECT * FROM shop_orders_lines WHERE delivery_id=?", $delivery['id']);
		foreach($delivery['lines'] as &$line) {
			$line['simpleattributes'] = $db->fetchAll("SELECT * FROM shop_orders_lines_simpleattributes WHERE line_id=? ORDER BY sort", $line['id']);
		}
		$order['delivery_price_excl_vat'] += $delivery['price_excl_vat'];
		$order['delivery_vat'] += $delivery['vat'];
	}
	
	$smarty->assign('order', $order);
	
	 // send confirmation emails
	$smarty->assign('sagepay', $sagepay);
	$mail = new Zend_Mail('UTF-8');
	if (file_exists("{$app_root}{$site['home_dir']}/templates/shop/emails/confirmation.tpl.text")) $mail->setBodyText($smarty->fetch("{$app_root}{$site['home_dir']}/templates/shop/emails/confirmation.tpl.text"));
	if (file_exists("{$app_root}{$site['home_dir']}/templates/shop/emails/confirmation.tpl.html")) $mail->setBodyHtml($smarty->fetch("{$app_root}{$site['home_dir']}/templates/shop/emails/confirmation.tpl.html"));
	$mail->setFrom($env['shop']['emails']['confirmation']['sender'], $env['shop']['emails']['confirmation']['sender_name']);
	$mail->addTo($sagepay->CustomerEmail, $sagepay->BillingFirstnames . ' ' . $sagepay->BillingSurname);
	$mail->setSubject(str_replace("__ORDERID__", $order['id'], $env['shop']['emails']['confirmation']['subject']));
	if (!$mail->send()) {
		$logger->crit("Customer email notification for order {$order_id} failed.");
	}
	$mail = new Zend_Mail('UTF-8');
	if (file_exists("{$app_root}{$site['home_dir']}/templates/shop/emails/notification.tpl.text")) $mail->setBodyText($smarty->fetch("{$app_root}{$site['home_dir']}/templates/shop/emails/notification.tpl.text"));
	if (file_exists("{$app_root}{$site['home_dir']}/templates/shop/emails/notification.tpl.html")) $mail->setBodyHtml($smarty->fetch("{$app_root}{$site['home_dir']}/templates/shop/emails/notification.tpl.html"));
	$mail->setFrom($sagepay->CustomerEmail, $sagepay->BillingFirstnames . ' ' . $sagepay->BillingSurname);
	$mail->addTo($env['shop']['emails']['notification']['recipient']);
	$mail->setSubject(str_replace("__ORDERID__", $order['id'], $env['shop']['emails']['notification']['subject']));
	if (!$mail->send()) {
		$logger->crit("Admin email notification for order {$order_id} failed.");
	}

	
	
	
}





$smarty->assign('sagepay_status', $sagepay->status());
$smarty->assign('sagepay_post_data', $sagepay_post_data);
$smarty->assign('errors', $errors);

switch ($sagepay->status()) {
	case 'OK':
		$smarty->display('shop/checkout_complete.tpl.html');
		break;
	case '3DAUTH':
		$smarty->display('shop/checkout_3dauth.tpl.html');
		break;
	default:
		$smarty->display('shop/checkout.tpl.html');
}

